//
//  ServerHelper.m
//  BSValue2
//
//  Created by Rainbow on 12/21/10.
//  Copyright 2010 iTotemStudio. All rights reserved.


#import "ServiceHelper.h"
#import "Reachability.h"
#import "CJSONDeserializer.h"
#import "CacheData.h"
#import "UtilHelper.h"
#import "Advertising.h"
#import "ImageInfo.h"

@implementation ServiceHelper

static ServiceHelper *_sharedInst = nil;
static NSString *ServerBaseUrl = SYDENY_BASE_URL;

+ (id) sharedService
{
	@synchronized(self){
		if(_sharedInst == nil)
		{
			_sharedInst = [[self alloc] init];
		}
	}
	return _sharedInst;
}

-(id) init
{
	if ((self = [super init])) {
		CallBacks = [[NSMutableDictionary alloc] init];
		[self restore];
	}
	return self;
}

-(void)requestDone:(ASIFormDataRequest *)request
{
	NSLog(@"feed back for action : %@, is : %@",request.requestFlagMark,[request responseString]);
	NSString *response = [request responseString];
    response = [response stringByReplacingOccurrencesOfString:@"\t\n" withString:@""];
    response = [response stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
	NSData *jsonData;
    if (response!= nil && ![@"" isEqualToString:response] && [[response substringWithRange:NSMakeRange(0,1)] isEqualToString: @"["] ) {
		jsonData = [[[@"{\"data\":" stringByAppendingString:response ] stringByAppendingString:@"}"] dataUsingEncoding:NSUTF8StringEncoding];
	}else {
		jsonData = [response  dataUsingEncoding:NSUTF8StringEncoding];
	}
    
	NSDictionary *result = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];    
	NSLog(@"result = %@", result);
	NSDictionary *targetCallBack = [CallBacks objectForKey:request.requestFlagMark];
	
	BOOL shouldTriggerErrorHandler = NO;
	if ([[result objectForKey:@"error_code"] intValue] == 100) {
		shouldTriggerErrorHandler = YES;
	}
    
	switch (request.RequestType) {
        case SydenyRequestGetAdvertising:
        {   
            NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *secondDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *thirdDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *forthDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *fifthDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *sixthDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *seventhDic = [[NSMutableDictionary alloc] init];
            
            NSArray *adsDic = [result objectForKey:@"advertising"];
            for (NSDictionary *adDic in adsDic) {
                Advertising *advertising = [[Advertising alloc] init];
                advertising.adId = [adDic objectForKey:@"ad_id"];
                advertising.image = [adDic objectForKey:@"image"];
                advertising.tabbar = [adDic objectForKey:@"tabbar"];
                advertising.index = [adDic objectForKey:@"ad_index"];
                
                advertising.shop.shopId = [UtilHelper getStringValue:[adDic objectForKey:@"shop_id"]];
                advertising.shop.title = [UtilHelper getStringValue:[adDic objectForKey:@"title"]];
                advertising.shop.name = [UtilHelper getStringValue:[adDic objectForKey:@"name"]];
                advertising.shop.address = [UtilHelper getStringValue:[adDic objectForKey:@"address"]];
                advertising.shop.telephone = [UtilHelper getStringValue:[adDic objectForKey:@"telephone"]];
                advertising.shop.createTime = [UtilHelper getStringValue:[adDic objectForKey:@"createtime"]];
                advertising.shop.email = [UtilHelper getStringValue:[adDic objectForKey:@"email"]];
                advertising.shop.latitude = [UtilHelper getStringValue:[adDic objectForKey:@"latitude"]];
                advertising.shop.longtitude = [UtilHelper getStringValue:[adDic objectForKey:@"longitude"]];
                advertising.shop.description = [UtilHelper getStringValue:[adDic objectForKey:@"description"]];
                advertising.shop.details = [UtilHelper getStringValue:[adDic objectForKey:@"details"]];
                
                NSArray *images = [adDic objectForKey:@"images"];
                for (NSDictionary *imageInfoDic in images) {
                    ImageInfo *imageInfo = [[ImageInfo alloc] init];
                    imageInfo.imageId = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"image_id"]];
                    imageInfo.imageUrl = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"imageurl"]];
                    imageInfo.thumbImagUrl = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"thumb_imageurl"]];
                    [advertising.shop.images addObject:imageInfo];
                    [imageInfo release];
                }

                
                switch ([advertising.tabbar intValue]) {
                    case 0:
                        [firstDic setObject:advertising forKey:advertising.index];
                        break;
                    case 1:
                        [secondDic setObject:advertising forKey:advertising.index];
                        break;
                    case 2:
                        [thirdDic setObject:advertising forKey:advertising.index];
                        break;
                    case 3:
                        [forthDic setObject:advertising forKey:advertising.index];
                        break;
                    case 4:
                        [fifthDic setObject:advertising forKey:advertising.index];
                        break;
                    case 5:
                        [sixthDic setObject:advertising forKey:advertising.index];
                        break;
                    case 6:
                        [seventhDic setObject:advertising forKey:advertising.index];
                        break;
                    default:
                        break;
                }
            }
            [[CacheData sharedData].advertisings setObject:firstDic forKey:@"0"];
            [[CacheData sharedData].advertisings setObject:secondDic forKey:@"1"];
            [[CacheData sharedData].advertisings setObject:thirdDic forKey:@"2"];
            [[CacheData sharedData].advertisings setObject:forthDic forKey:@"3"];
            [[CacheData sharedData].advertisings setObject:fifthDic forKey:@"4"];
            [[CacheData sharedData].advertisings setObject:sixthDic forKey:@"5"];
            [[CacheData sharedData].advertisings setObject:seventhDic forKey:@"6"];
            
        }
            break;    
        default:
            break;
    }
	
	if(shouldTriggerErrorHandler){
		[[targetCallBack objectForKey:@"delegate"] performSelector:NSSelectorFromString([targetCallBack objectForKey:@"onfailed"]) withObject:@"auth error"];
	}else {
		[[targetCallBack objectForKey:@"delegate"] performSelector:NSSelectorFromString([targetCallBack objectForKey:@"onsuccess"]) withObject:result];
	}
	
	[CallBacks removeObjectForKey:request.requestFlagMark];
}

-(void)requestWentWrong:(ASIFormDataRequest *)request
{
	NSDictionary *targetCallBack = [CallBacks objectForKey:request.requestFlagMark];
	NSLog(@"request %@ went wrong with status code %d, and feedback body %@",request.requestFlagMark, [request responseStatusCode], [request responseString]);
	[[targetCallBack objectForKey:@"delegate"] performSelector:NSSelectorFromString([targetCallBack objectForKey:@"onfailed"]) withObject:@"connection error"];
	[CallBacks removeObjectForKey:request.requestFlagMark];
}

-(ASIFormDataRequest *)requestServerForMethod:(SydenyRequestType)methodType 
							   WithParameters:(NSDictionary *)parameters 
							AndCallBackScope:(id)callBackDelegate 
								AndSuccessSel:(NSString *)successSelector 
								 AndFailedSel:(NSString *)failedSelector
{
	NSDictionary *tempDic = [NSDictionary dictionaryWithObjectsAndKeys:callBackDelegate, @"delegate", successSelector, @"onsuccess", failedSelector, @"onfailed", nil];
	[tempDic retain];
	
    NSString *requestUrl = @"";
    switch (methodType) {
        case SydenyRequestGetShops:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getshops.php?"];
            break;
        case SydenyRequestGetAdvertising:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getadvertising.php?"];
            break;
        case SydenyRequestAddComments:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/addcomment.php?"];
            break;
        case SydenyRequestGetComments:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getcomments.php?"];
            break;
        case SydenyRequestLogin:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/login.php?"];
            break;
        case SydenyRequestRegister:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/registeruser.php?"];
            break;   
        case SydenyRequestGetCollectMost:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getcollectmost.php?"];
            break;  
        case SydenyRequestGetRank:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getrank.php?"];
            break;  
        case SydenyRequestGetWeekHot:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getweekhot.php?"];
            break; 
        case SydenyRequestGetCollectMostShop:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getcollectmostshop.php?"];
            break;  
        case SydenyRequestGetWeekHotShop:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/getweekhotshop.php?"];
            break;  
        case SydenyRequestSetNotification:
            requestUrl = [ServerBaseUrl stringByAppendingString:@"/setnotification.php?"];
            break;    
        default:
            break;
    }

    NSArray *paraKeys = [parameters allKeys];
    if([paraKeys count] > 0)
    {
        for(NSInteger i = 0; i < [paraKeys count] ; i++)
        {

            if (i == [paraKeys count] - 1) {
                requestUrl = [requestUrl stringByAppendingFormat:@"%@=%@",[paraKeys objectAtIndex:i],[parameters objectForKey:[paraKeys objectAtIndex:i]]];
            }
            else
            {
                requestUrl = [requestUrl stringByAppendingFormat:@"%@=%@&",[paraKeys objectAtIndex:i],[parameters objectForKey:[paraKeys objectAtIndex:i]]];
            }
        }
    }
    
    NSLog(@"requestUrl: %@", requestUrl);
    
	ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    
    //Add header parameters for ZhiYue
    [request addRequestHeader:@"App" value:@"ipad"];
    [request addRequestHeader:@"Device" value:[UIDevice currentDevice].uniqueIdentifier];
	request.requestFlagMark = [self getTimeStamp];
	request.RequestType = methodType;
	request.responseEncoding = NSUTF8StringEncoding;
	[CallBacks setObject:tempDic forKey:request.requestFlagMark];
	
	[tempDic release];
	[request setDelegate:self];
	[request setDidFinishSelector:@selector(requestDone:)];
	[request setDidFailSelector:@selector(requestWentWrong:)];
    [request setRequestMethod:@"GET"];
	[request startAsynchronous];
    [request setTimeOutSeconds:30];
	return request;
}
-(BOOL)checkNetwork:(NSString *)errorMessage
{
	Reachability *reachAblility = [Reachability reachabilityForInternetConnection];
	
	if (![reachAblility isReachable]) {
		if (errorMessage == nil) {
			return NO;
		}
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"无网络连接", @"") message:errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil];
		[alertView show];
		[alertView release];
		return NO;
	}
	return YES;
	
}

-(NSString *)getTimeStamp{
	NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
	return [NSString stringWithFormat:@"%u",timestamp];
}

- (NSUInteger)retainCount{
	return NSUIntegerMax;
}

- (oneway void)release{
}

- (id)retain{
	return _sharedInst;
}

- (id)autorelease{
	return _sharedInst;
}

- (void) restore{
	
}

-(void) dealloc
{
	[CallBacks release];
	[super dealloc];
}

@end
